package com.mgs.product.tagger.dao
{
	import com.mgs.product.tagger.model.Preferences;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class PreferencesDaoImpl implements PreferencesDao
	{
		public function PreferencesDaoImpl()
		{
		}
		
		public function load():Preferences
		{
			var stream:FileStream = new FileStream();
			var file:File = File.applicationStorageDirectory.resolvePath("preferences.xml");
			var preferences:Preferences = new Preferences();
			if(file.exists)
			{
				stream.open(file, FileMode.READ);
				
				var str:String = stream.readUTFBytes(file.size);
				
				stream.close();
				
				var xml:XML = new XML(str);

				if(xml.@defaultRepository.toString() != "")
				{
					preferences.defaultRepository = File.desktopDirectory.resolvePath(xml.@defaultRepository.toString());
				}
			}
			return preferences;
		}
		
		public function save(preferences:Preferences):void
		{
			var root:XML = <preferences/>;
			if(preferences.defaultRepository != null)
			{
				var absolutePath:String = preferences.defaultRepository.nativePath
				root.@defaultRepository = absolutePath;
			}
			var stream:FileStream = new FileStream();
			stream.open(File.applicationStorageDirectory.resolvePath("preferences.xml"), FileMode.WRITE);
			
			stream.writeUTFBytes(root.toXMLString());
			
			stream.close();
			
		}
	}
}